function setDate(objEnddate, days){
    var dt = new Date(parseInt($dp.cal.getP('y')), parseInt($dp.cal.getP('M'))-1, parseInt($dp.cal.getP('d'))+days);
    objEnddate.value = dt.format("yyyy-MM-dd");
}

$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		
		$("#orderItemsTable").jqGrid({						
			url : appRoot + '/commercialInvoiceItem/list/' + commercialInvoiceId + '?ajax=1',
			editurl : appRoot + '/commercialInvoiceItem/save?ajax=1&commercialInvoiceId=' + commercialInvoiceId,
			datatype : 'json',
			mtype : 'GET',
			jsonreader: {             
				repeatitems: false,
				id:'Id',
				root:'rows'
			}, 
			colNames : [ 'id','objectId','orderItemId','编号', '名称', '单价', '数量','单位','总计'], 
			colModel : [
	       {
				name : 'id',
				index : 'id',
				editable : true,
				hidden:true
				
			}, {
				name : 'objectId',
				index : 'objectId',
				editable : true,
				hidden:true
			}, {
				name : 'orderItemId',
				index : 'orderItemId',
				editable : true,
				hidden:true
			},{
				name : 'customerPerchaseNo',
				index : 'customerPerchaseNo',
				width : 140,
				align : 'left',
				resizable : false,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}

			}, {
				name : 'productDecription',
				index : 'productDecription',
				width : 300,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}
			}, {
				name : 'unitPrice',
				index : 'unitPrice',
				width : 60,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}
			}, {
				name : 'quantity',
				index : 'quantity',
				width : 60,
				align : 'right',
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}							
			}, {
				name : 'unit',
				index : 'unit',
				width : 40,
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :units
			    },
				editrules : {
					required : true
				}
			}, {
				name : 'amount',
				index : 'amount',
				width : 100,
				align : 'right',
				editable : false,
				sortable: false,
				editrules : {
					number : true
				}
			}
			],
			gridComplete: function(){
				var grid = $("#orderItemsTable");
				var sumQuantity = grid.jqGrid('getCol', 'quantity', false, 'sum'); 
				var sumAmount = grid.jqGrid('getCol', 'amount', false, 'sum'); 
				grid.jqGrid('footerData','set', {unitPrice:"合计:", quantity: sumQuantity,amount:sumAmount}); 
			},
			width: 730,
			height : 200,
			pager : $('#pager'),
			nowNum : 100,
			rowNum : 100,
			sortname : 'id',
			viewrecords : true,
			footerrow: true,
			shrinkToFit:false,
			caption : ''
		}).navGrid("#pager",{edit:true,add:false,del:true,search:false});

		$("#orderChargeTable1").jqGrid({                       
	        url : appRoot + '/commercialInvoiceCharge/list/1/' + commercialInvoiceId + '?ajax=1', 
	        editurl : appRoot + '/commercialInvoiceCharge/save?ajax=1&type=1&commercialInvoiceId=' +commercialInvoiceId,
	        datatype : 'json',
	        mtype : 'GET',
	        jsonreader: {             
	            repeatitems: false,
	            id:'Id',
	            root:'rows'
	        }, 
	        
	        colNames : [ 'id','objectId','收费项目', '金额'],
	        colModel : [
	       {
	            name : 'id',
	            index : 'id',
	            editable : true,
	            hidden:true
	            
	        }, {
	            name : 'objectId',
	            index : 'objectId',
	            editable : true,
	            hidden:true
	        },{
	            name : 'chargeName',
	            index : 'chargeName',
	            width : 100,
	            align : 'left',
	            resizable : false,
	            editable : true,
	            edittype:'text',
	            editoptions:{
	                cols:21,rows:3
	            },
	            sortable: false,
	            editrules : {
	                required : true
	            }

	        }, {
	            name : 'charge',
	            index : 'charge',
	            width : 60,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true,
	                number : true
	            }
	        }
	        ],
	        gridComplete: function(){
	            var grid = $("#orderChargeTable1");
	            sum = grid.jqGrid('getCol', 'charge', false, 'sum'); 
	            grid.jqGrid('footerData','set', {chargeName:"合计:", charge: sum}); 
	        },
	        width: 730,
	        height : 100,
	        pager : $('#pager1'),
	        nowNum : 100,
	        rowNum : 100,
	        sortname : 'id',
	        viewrecords : true,
	        footerrow: true,
	        caption : '额外费用明细'
	    }).navGrid("#pager1",{edit:true,add:true,del:true,search:false});
		
		$("#orderChargeTable2").jqGrid({                       
	        url : appRoot + '/commercialInvoiceCharge/list/2/' + commercialInvoiceId + '?ajax=1', 
	        editurl : appRoot + '/commercialInvoiceCharge/save?ajax=1&type=2&commercialInvoiceId=' +commercialInvoiceId,
	        datatype : 'json',
	        mtype : 'GET',
	        jsonreader: {             
	            repeatitems: false,
	            id:'Id',
	            root:'rows'
	        }, 
	        
	        colNames : [ 'id','objectId','扣费项目', '金额'],
	        colModel : [
	       {
	            name : 'id',
	            index : 'id',
	            editable : true,
	            hidden:true
	            
	        }, {
	            name : 'objectId',
	            index : 'objectId',
	            editable : true,
	            hidden:true
	        },{
	            name : 'chargeName',
	            index : 'chargeName',
	            width : 100,
	            align : 'left',
	            resizable : false,
	            editable : true,
	            edittype:'text',
	            editoptions:{
	                cols:21,rows:3
	            },
	            sortable: false,
	            editrules : {
	                required : true
	            }

	        }, {
	            name : 'charge',
	            index : 'charge',
	            width : 60,
	            editable : true,
	            edittype:'text',
	            sortable: false,
	            editrules : {
	                required : true,
	                number : true
	            }
	        }
	        ],
	        gridComplete: function(){
	            var grid = $("#orderChargeTable2");
	            sum = grid.jqGrid('getCol', 'charge', false, 'sum'); 
	            grid.jqGrid('footerData','set', {chargeName:"合计:", charge: sum}); 
	        },
	        width: 730,
	        height : 100,
	        pager : $('#pager2'),
	        nowNum : 100,
	        rowNum : 100,
	        sortname : 'id',
	        viewrecords : true,
	        footerrow: true,
	        caption : '扣费明细'
	    }).navGrid("#pager2",{edit:true,add:true,del:true,search:false});
		
	}catch(e){}
	
	$(".colorbox").colorbox({iframe:true, innerWidth:750, innerHeight:460});
	$("#type").change(function(){
        var type = $(this).val();
        if(type==9){
            $("#byOthers").show();
        }else{
            $("#byOthers").val("");
            $("#byOthers").hide();
        }
    });
    $("#type").change();
    
	$("#orderId").change(function(){
        var orderId = $(this).val();
        if(orderId){
            if(confirm("需要导入该订单的明细数据吗？")){
                $("#notice").html("数据导入中...").show();
                 $.ajax({
                     url: appRoot + "/orderItem/importToCommercialInvoice/" + commercialInvoiceId + "?orderIds=" + orderId + "&date=" + (new Date()).valueOf(),
                     type:'post',
                     dataType:'json',
                     success:function(msg){
                         if(msg.result){
                             $("#orderItemsTable").trigger("reloadGrid");
                             $("#notice").html("成功导入" + msg.result + "条订单明细");
                         }else{
                        	 $("#notice").html("没有明细需要导入");
                         }
                     }
                });
            }
        }
    });
	 
});

//Page
function getCustomer(id){
    $("#suberror").hide();
    $("#subnotice").hide();
    $("#otherUsers").val("");
    $("input[type='checkbox']").each(function(){
        $(this).attr("checked",false);
    });
    if(id){
        $.ajax({
             url: appRoot + "/customer/get/" + id,
             type:'post',
             dataType:'json',
             success:function(msg){
                 $("#customer_2").text(msg.entity.name).attr("title",msg.entity.email);
             }
        });
    }
}


function notify(){
    if(currentOrderId==null){
        return;
    }
    $(".audit").attr("disabled",true);
    $("#notifyButton").attr("disabled",true);
    var selected = getCheckedValuesString(document.getElementsByName("users"));
    var customer = ($("#customer_1").attr("checked")=="checked");
    var others = $("#otherUsers").val();
    if(!selected&&!customer&&!others){
        $("#suberror").html("请至少选择一个接收者").show();
        $(".audit").attr("disabled",false);
        $("#notifyButton").attr("disabled",false);
    }else{
        $("#suberror").hide();
        $("#subnotice").html("操作进行中...").show();
        $.ajax({
             url: appRoot + "/commercialInvoice/notify/" + currentOrderId + "?date=" + (new Date()).valueOf(),
             type:'post',
             dataType:'json',
             data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
             success:function(msg){
                 if(msg.result){
                     showMessage("邮件已发送");
                 }else{
                     showMessage("操作失败");
                 }
                 $(".audit").attr("disabled",false);
                 $("#notifyButton").attr("disabled",false);
                 jQuery.fn.colorbox.close();
             }
        });
    }
}

function pay(orderId,action){
    $(".audit").attr("disabled",true);
    if(confirm("你确认已收款？")){
    	$.ajax({
            url: appRoot + "/commercialInvoice/pay/" + orderId,
            type:'post',
            dataType:'json',
            success:function(msg){
                if(msg.result){
                    window.location.href= appRoot + '/commercialInvoice/' + action + '?message=' + encodeURIComponent('操作成功');
                }else{
                    showMessage("操作失败");
                    $(".audit").attr("disabled",false);
                }
            }
       });
    }
}

function audit(orderId,action){
	$("#notice").html("操作进行中...").show();
    $(".audit").attr("disabled",true);
    $.ajax({
         url: appRoot + "/commercialInvoice/audit/" + orderId,
         type:'post',
         dataType:'json',
         data:"status=20" ,
         success:function(msg){
             if(msg.result){
                 window.location.href= appRoot + '/commercialInvoice/' + action + '?message=' + encodeURIComponent('操作成功');
             }else{
            	 $("#notice").html("").hide();
                 showMessage("操作失败");
                 $(".audit").attr("disabled",false);
             }
         }
    });
}

function backward(action){
	if(currentOrderId==null){
		return;
	}
	var reason = $("#reason").val();
    if(!reason){
    	$("#suberror1").html("请填写退回原因").show();
    	return;
    }
	$("#subnotice1").html("操作进行中...").show();
	$("#suberror1").html("").hide();
	$(".bacward").attr("disabled",true);
	$("#backwardButton").attr("disabled",true);
	$.ajax({
         url: appRoot + "/commercialInvoice/backward/" + currentOrderId + "?reason=" +  encodeURIComponent(reason) + "&date=" + (new Date()).valueOf(),
         type:'post',
         dataType:'json',
         success:function(msg){
        	 if(msg.result){
        		 window.location.href= appRoot +'/commercialInvoice/' + action + '?message=' + encodeURIComponent('操作成功');
        	 }else{
        		 var message = msg.message;
        		 if(message==null){
        			 message = "操作失败";
        		 }
        		 $("#subnotice1").html("").hide();
        		 $("#suberror1").html(message).show();
        		 $(".bacward").attr("disabled",false);
        		 $("#backwardButton").attr("disabled",false);
        	 }
         }
	});
}

